// 简化版本的 GitCode 问题反馈插件
console.log('🚀 GitCode 问题反馈插件开始加载...');

// BugReporter 类
class BugReporter {
    constructor(issueURL) {
        this.issueURL = issueURL;
        this.title = '';
        this.body = '';
        this.labels = 'BugReport';
    }

    getSelectedText() {
        if (window.getSelection) {
            const selection = window.getSelection();
            return selection ? selection.toString() : '';
        } else if (document.selection && document.selection.type === 'Text') {
            return document.selection.createRange().text;
        }
        return '';
    }

    setTitle(title) {
        this.title = title || '';
    }

    setBody(body) {
        this.body = body || '';
    }

    report() {
        const params = new URLSearchParams({
            title: this.title,
            body: this.body,
            labels: this.labels
        });
        
        const url = `${this.issueURL}?${params.toString()}`;
        window.open(url, '_blank');
    }
}

// 创建反馈按钮
function createFeedbackButton(config) {
    console.log('🔧 创建反馈按钮...', config);
    
    const reportElement = document.createElement('button');
    reportElement.textContent = config.label || 'Bug Report';
    reportElement.className = 'gitbook-plugin-gitcode-issue-feedback';
    reportElement.setAttribute('aria-label', 'Report an issue on GitCode');
    reportElement.setAttribute('title', 'Click to report an issue about this page');
    
    // 添加样式
    reportElement.style.cssText = `
        position: fixed;
        right: 20px;
        bottom: 20px;
        z-index: 1000;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 25px;
        padding: 12px 20px;
        font-size: 14px;
        font-weight: 600;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        transition: all 0.3s ease;
        user-select: none;
    `;
    
    const clickEvent = ('ontouchstart' in window) ? 'touchend' : 'click';
    
    reportElement.addEventListener(clickEvent, async (event) => {
        event.preventDefault();
        
        // Add loading state
        reportElement.classList.add('loading');
        reportElement.textContent = 'Loading...';
        
        try {
            // 获取当前页面信息
            const pathname = window.location.pathname || './';
            const chapterTitle = document.title || 'Page';
            const bug = new BugReporter(`https://gitcode.com/${config.repo}/issues/new`);
            const selectedText = bug.getSelectedText().trim();
            
            bug.setTitle(chapterTitle);
            
            let body = `URL: ${window.location.href}\n\n`;
            
            if (selectedText && selectedText.length > 0) {
                body += `选中的文本：\n\`\`\`\n${selectedText}\n\`\`\`\n\n`;
            }
            
            bug.setBody(body);
            bug.report();
            
            // Success state
            reportElement.classList.remove('loading');
            reportElement.classList.add('success');
            reportElement.textContent = 'Issue Created!';
            
            setTimeout(() => {
                reportElement.classList.remove('success');
                reportElement.textContent = config.label || 'Bug Report';
            }, 2000);
            
        } catch (error) {
            console.error('GitCode Issue Feedback Error:', error);
            
            // Error state
            reportElement.classList.remove('loading');
            reportElement.classList.add('error');
            reportElement.textContent = 'Error!';
            
            setTimeout(() => {
                reportElement.classList.remove('error');
                reportElement.textContent = config.label || 'Bug Report';
            }, 3000);
        }
    });
    
    document.body.appendChild(reportElement);
    console.log('✅ 反馈按钮已创建');
}

// 初始化插件
function initPlugin() {
    console.log('🔧 初始化插件...');
    
    const config = {
        repo: 'nutpi/gitbook-plugin-gitcode-issue-feedback',
        label: '报告问题',
        private: false
    };
    
    createFeedbackButton(config);
}

// 等待 DOM 准备好
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initPlugin);
} else {
    initPlugin();
}

console.log('✅ GitCode 问题反馈插件加载完成');
